import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

import {RouterService} from '@kylin/router';
import {LoginService} from './login.service';
import {NzMessageService} from 'ng-zorro-antd';
import {CacheService} from '@kylin/cache';
import {environment} from '../../environments/environment';

@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less']
})

export class LoginComponent implements OnInit, AfterViewInit {

    loginForm: FormGroup;
    loading = false;
    state = true;
    @ViewChild('verificationCode', {static: true}) verificationCode;

    constructor(private routerService: RouterService,
                private fb: FormBuilder,
                private loginService: LoginService,
                private message: NzMessageService,
                private cacheService: CacheService
    ) {

    }

    /**
     * 此方法用创建响应式表单
     */
    ngOnInit(): void {
        this.loginFormInit();
    }

    ngAfterViewInit(): void {

    }

    private loginFormInit() {
        let identity = '13888888888';
        let password = '123456';
        if (environment.production) {
            identity = '';
            password = '';
        }
        this.loginForm = this.fb.group({
            identity: [identity, [Validators.required]],
            password: [password, [Validators.required]],
        });
    }

    /**
     * 此方法用来提交登陆表单
     */
    submitForm(): void {
        if (!this.loginForm.valid) {
            return;
        }
        this.loading = true;
        const data = this.loginForm.value;
        this.loginService.doLogin(data)
            .then(res => {
                this.loading = false;
                if (res.status === 200) {
                    this.cacheService.set('token', res.result.user.token);
                    this.routerService.navigate('/home');
                } else {
                    this.message.create('error', res.message);
                }
            })
            .catch(err => {
                this.loading = false;
                this.message.create('error', `登陆失败`);
            });
    }

}

